//
//  DrugDetailViewController.m
//  安好
//
//  Created by 冯凯 on 14-12-4.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "DrugDetailViewController.h"
#import "DrugSeDetailViewController.h"
#import "DrugBaseDetailViewController.h"

@interface DrugDetailViewController ()
{
    FKSearchBar * illSeachBar;
}
@end

@implementation DrugDetailViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 取消输入框
    [illSeachBar.searchTextField resignFirstResponder];
    [self setEditing:NO animated:YES];
    
    [illSeachBar.searchTextField removeTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    [[AFHTTPRequestOperationManager manager].operationQueue cancelAllOperations];
    [self hiddenActionView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.encyArray = [[NSMutableArray alloc]init];
    self.searchArray = [[NSMutableArray alloc]init];

    self.catPage = 1;
    [self makeNavBar];
    [self loadData];
    [self makeTableView];
    [self creatSearchTableView];
    [self markIllnessSearchBar];
    
}
#pragma - mark searchBar
- (void)markIllnessSearchBar
{
    illSeachBar = [[FKSearchBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    illSeachBar.searchTextField.placeholder = @"药品";
    illSeachBar.searchTextField.delegate = self;
    illSeachBar.fkSearchRequestDelegate = self;
    [self.view addSubview:illSeachBar];
    [illSeachBar.searchTextField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];

}
- (void)loadData
{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    if ([self.searchcat length] == 0){
        
    }else{
        [dict setObject:self.searchcat forKey:@"keyword"];
    }
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)self.catPage] forKey:@"page"];
    [dict setObject:self.catid forKey:@"pid"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@wiki/drugCategory",kBaseURL] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self.tableView footerEndRefreshing];
        }else{
            if (self.isSearch == YES){
                if ([self.encyArray count] != 0){
                    [self.encyArray removeAllObjects];
                }
            }
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            if (jsonDictArr!=nil) {
                self.catPage++;
                for (NSDictionary * dic in jsonDictArr){
                    [self.encyArray addObject:dic];
                }
                [self.tableView reloadData];
            }
            [self.tableView footerEndRefreshing];

        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.tableView footerEndRefreshing];

    }];
    
}
#pragma mark - 导航条的布局
-(void)makeNavBar
{
    self.navigationItem.title = @"药品";
    //贴 返回 按钮的图片
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;
}
-(void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 创建tableView 设置table的代理、添加头视图横线
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, kScreenWidth, kScreenHeight-iOS7TopMargin-TABBAR_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView addFooterWithTarget:self action:@selector(loadData)];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];
    self.tableView.hidden = NO;

}

- (void)creatSearchTableView{
    self.searchTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, kScreenWidth, kScreenHeight-iOS7TopMargin-TABBAR_HEIGHT) style:UITableViewStylePlain];
    self.searchTable.delegate = self;
    self.searchTable.dataSource = self;
    //隐藏横向和竖向的滑条
    self.searchTable.showsHorizontalScrollIndicator = NO;
    self.searchTable.showsVerticalScrollIndicator = NO;
    [self.searchTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.searchTable];    
    self.searchTable.hidden = YES;
    
}
#pragma mark - tableView的代理方法
/**
 *  设置 各行cell高
 */
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.searchTable) {
        return 35;
    }
    if (kScreenWidth == 414){
        return 56;

    }else{
        
        return 46;
    }
}
/**
 *  设置 头视图的行高
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{


    return 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchTable) {
        return self.searchArray.count;
    }

    return self.encyArray.count;
}
#pragma mark --cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tableView == tableView) {
        
    
    static NSString * identifier = @"myCell";
    
    
    //  检测、查询是否有闲置的单元格
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell =  [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.textLabel.font = [UIFont systemFontOfSize:TITLE_TEXTLABEL_FOUNT_SIZE];
    cell.textLabel.textColor = [UIColor colorWithRed:31.0/255 green:33.0/255 blue:36.0/255 alpha:1];
    cell.textLabel.text = [[self.encyArray objectAtIndex:indexPath.row] objectForKey:@"catname"];
   
    UIImageView * upImageView = [[UIImageView alloc]initWithFrame:CGRectMake(15, 45, kScreenWidth - 15, 0.5)];
        if (kScreenWidth == 414){
            upImageView.frame = CGRectMake(20, 56.5, kScreenWidth - 20, 0.5);
        }else{
            upImageView.frame = CGRectMake(15, 45, kScreenWidth - 15, 0.5);

        }
    upImageView.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#c8c8c8"];
    [cell addSubview:upImageView];

    
    //  返回每行的单元格对象
    return cell;
    }else{
        static NSString *reuseIdetify = @"SvTableViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdetify];
        }
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
        cell.textLabel.text = [self.searchArray objectAtIndex:indexPath.row];
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.searchTable) {
        
        illSeachBar.searchTextField.text = [self.searchArray objectAtIndex:indexPath.row];
        [self.view endEditing:YES];
        

        
        
        [self SearchString];
        
        return;
    }
    if (self.isHealthCat == NO) {
        DrugSeDetailViewController *encyDrugSecondVC = [[DrugSeDetailViewController alloc] init];
        encyDrugSecondVC.catid = TextString([[self.encyArray objectAtIndex:indexPath.row] objectForKey:@"catid"]);
        encyDrugSecondVC.catname = TextString([[self.encyArray objectAtIndex:indexPath.row] objectForKey:@"catname"]);
        [self.navigationController pushViewController:encyDrugSecondVC animated:YES];
    }
    else if (self.isHealthCat == YES){
        DrugBaseDetailViewController *encyDrugMedicineVC = [[DrugBaseDetailViewController alloc]init];
        encyDrugMedicineVC.catid = TextString([[self.encyArray objectAtIndex:indexPath.row] objectForKey:@"catid"]);
        encyDrugMedicineVC.catname = TextString([[self.encyArray objectAtIndex:indexPath.row] objectForKey:@"catname"]);
        [self.navigationController pushViewController:encyDrugMedicineVC animated:YES];
    }
}
#pragma - mark FKSearchDelegate
/**
 *  FKSearch的delegate
 */
- (void)VoiceConversion
{
    [illSeachBar.searchTextField resignFirstResponder];
    [self starVoice];
}
- (void)voice:(NSString *)voice
{
    illSeachBar.searchTextField.text = voice;
    self.isSearch = YES;
    self.catPage = 1;
    self.searchcat = voice;
    [self loadData];
}
- (void)SearchString
{
    [illSeachBar.searchTextField resignFirstResponder];
    self.isSearch = YES;
    self.catPage = 1;
    self.searchcat = illSeachBar.searchTextField.text;
    
    if (self.searchcat.length>0) {
        DrugBaseDetailViewController *drugBaseDVC = [[DrugBaseDetailViewController alloc]init];
        drugBaseDVC.searchcat =  self.searchcat;
        drugBaseDVC.title = @"查找的药品";
        [self.navigationController pushViewController:drugBaseDVC animated:YES];
    }
 
    
//    [self loadData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (!self.tableView.hidden) {
        self.tableView.hidden = YES;
        self.searchTable.hidden = NO;
        
        
    }
    
    return YES;
    
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (!self.searchTable.hidden) {
        self.tableView.hidden = NO;
        self.searchTable.hidden = YES;
        
        
    }
}
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    if (!self.searchTable.hidden) {
//        
//        //    [self.searchArray addObject:textField.text];
//        //        [self.searchTable reloadData];
//        [self loadsearchData:textField.text];
//    }
//    return YES;
//}

- (void)textFieldEditChanged:(UITextField *)textField
{
    if (!self.searchTable.hidden) {

        [self loadsearchData:textField.text];
    }
    MyNSLog("textField text : %@", [textField text]);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (!self.searchTable.hidden) {
        
        [self SearchString];

    }
    return YES;
}
-(void)loadsearchData:(NSString*)text{
    
    
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setValue:text forKey:@"q"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [[manager operationQueue] cancelAllOperations];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,AUTO_DRUG] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        [self.searchArray removeAllObjects];

        if ([statusString isEqualToString:@"0"]) {
        }else{
            
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            MyNSLog("%@", jsonDictArr);

            for (NSDictionary *objc in jsonDictArr) {
                [self.searchArray addObject:objc];
            }
        }
        [self.searchTable reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.searchTable reloadData];
        
    }];
    
}


@end
